package com.xmall.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xmall.bean.table.Topic;
import com.xmall.bean.table.TopicExample;
import com.xmall.mapper.TopicMapper;
import com.xmall.service.TopicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TopicServiceImpl implements TopicService {

    @Autowired
    TopicMapper topicMapper;
    @Override
    public Map<String, Object> queryList(Map<String, String> params) {
        PageHelper.startPage(Integer.parseInt(params.get("page")),Integer.parseInt(params.get("limit")));
        TopicExample topicExample = new TopicExample();
        topicExample.setOrderByClause(params.get("sort") + " " + params.get("order"));
        TopicExample.Criteria criteria = topicExample.createCriteria();

        if (params.get("title") != null){
            criteria.andTitleLike("%" + params.get("title") +"%");
        }
        if (params.get("subtitle") != null){
            criteria.andSubtitleLike("%" + params.get("subtitle") + "%");
        }
        criteria.andDeletedEqualTo(false);

        List<Topic> topics = topicMapper.selectByExample(topicExample);
        PageInfo<Topic> topicPageInfo = new PageInfo<>(topics);
        long total = topicPageInfo.getTotal();
        HashMap<String, Object> result = new HashMap<>();
        result.put("total",total);
        result.put("items",topics);
        return result;
    }

    @Override
    public Topic createTopic(Topic create) {
        create.setAddTime(new Date());
        create.setUpdateTime(new Date());
        topicMapper.insertSelective(create);
        return create;
    }

    @Override
    public Topic updateTopic(Topic update) {
        update.setUpdateTime(new Date());
        topicMapper.updateByPrimaryKeySelective(update);
        return update;
    }

    @Override
    public void deleteTopic(Topic delete) {
        delete.setDeleted(true);
        updateTopic(delete);
    }
}
